package com.carpedil.ms.service.impl;

import com.carpedil.ms.entity.Order;
import com.carpedil.ms.entity.Stock;
import com.carpedil.ms.entity.User;
import com.carpedil.ms.mapper.OrderMapper;
import com.carpedil.ms.mapper.StockMapper;
import com.carpedil.ms.service.OrderService;
import com.carpedil.ms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/** @author Administrator */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
  @Autowired private StockMapper stockMapper;
  @Autowired private OrderMapper orderMapper;
  @Autowired private UserService userService;
  @Autowired private StringRedisTemplate redisTemplate;

  @Override
  public String getMd5(String username, String password, Integer id) {
    // 验证用户id
    User user = userService.checkUser(username, password);
    if (user == null) {
      throw new RuntimeException("用户不存在");
    }
    log.info("用户信息:[{}]", user.toString());
    // 验证商品id
    Stock stock = stockMapper.checkStockById(id);
    if (stock == null) {
      throw new RuntimeException("商品信息不存在");
    }
    log.info("商品信息:[{}]", stock.toString());
    // 生成hashkey
    String hashKey = "KEY_" + username + "_" + id;

    // 生成md5   !QS#是一个随机盐
    String md5 = DigestUtils.md5DigestAsHex((username + id + "!Q*jS#").getBytes());
    redisTemplate.opsForValue().set(hashKey, md5, 240, TimeUnit.SECONDS);
    log.info("redis写入:[{}],[{}]", hashKey, md5);
    return md5;
  }

  @Override
  public String kill(Integer id, String username, String md5) {
    // 校验redis中秒杀商品是否超时 如果超时,抛出异常
    if (!redisTemplate.hasKey("kill" + id)) {
      return "该商品的秒杀时间已经过期啦~~";
    }
    // 校验md5
    String hashKey = "KEY_" + username + "_" + id;
    if (!redisTemplate.opsForValue().get(hashKey).equals(md5)) {
      return "用户信息不合法,请稍后重试~~";
    }
    // 根据商品id校验库存
    Stock stock = checkStock(id);
    // 减扣库存
    updateSale(stock);
    // 创建订单
    return String.valueOf(createOrder(stock, username));
  }

  @Override
  public List<Order> checkOrderByUserName(String username) {
    return orderMapper.checkOrderByUserName(username);
  }

  private Stock checkStock(Integer id) {
    // 根据商品id校验库存
    Stock stock = stockMapper.checkStockById(id);
    if (stock.getCount().equals(stock.getSale())) {
      throw new RuntimeException("库存不足");
    }
    return stock;
  }

  private void updateSale(Stock stock) {
    // 减扣库存
    int updateRowCount = stockMapper.updateStock(stock);
    if (updateRowCount == 0) {
      throw new RuntimeException("活动过于火爆,服务器爆满,请重试!!!");
    }
  }

  private int createOrder(Stock stock, String username) {
    Order order = new Order();
    order
        .setSid(stock.getId())
        .setName(stock.getName())
        .setCreateTime(LocalDateTime.now())
        .setUser(username);
    // 创建订单
    orderMapper.createOrder(order);
    // 返回订单id
    return order.getId();
  }
}
